package br.com.lojapi.controle;

import br.com.lojapi.bean.Cliente;
import br.com.lojapi.bean.Endereco;
import br.com.lojapi.bean.Perfil;
import br.com.lojapi.dao.ClienteDAO;
import br.com.lojapi.dao.ClienteDAOImp;
import br.com.lojapi.dao.PerfilDAO;
import br.com.lojapi.dao.PerfilDAOImp;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Aluno
 */
@WebServlet(name = "ClienteServlet", urlPatterns = {"/cliente_do"})
public class ClienteServlet extends HttpServlet {

    private HttpServletRequest request;
    private HttpServletResponse response;
    private RequestDispatcher rd;
    private ClienteDAO clienteDAO;
    private Cliente cliente;
    private PerfilDAO perfilDAO;

    protected void processRequest() throws ServletException, IOException {
        String cmd = request.getParameter("cmd");
        switch (cmd) {
            case "salvar":
                salvar();
                break;
            case "pesquisaPorNome":
                pesquisaPorNome();
                break;
            case "carregaCombo":
                carregaCombo();
                break;
            case "alterar":
                altera();
                break;
            case "carregaCliente":
                pesquisaClientePorId();
                break;
        }
        rd.forward(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void salvar() {
        carregaCliente();
        clienteDAO = new ClienteDAOImp();
        try {
            clienteDAO.salvar(cliente);
            request.setAttribute("msg", "Cliente salvo com sucesso!");
            rd = request.getRequestDispatcher("index.jsp");
        } catch (Exception ex) {
            Logger.getLogger(ClienteServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        request.setAttribute("msg", "Cliente salvo com sucesso!");
        rd = request.getRequestDispatcher("/index.jsp");
    }

    private void carregaCliente() {
        cliente = new Cliente();
        Endereco endereco = new Endereco();
        Perfil perfil = new Perfil();
        String id = request.getParameter("id");
        if (id != null) {
            cliente.setId(Integer.parseInt(id));
        }
        cliente.setNome(request.getParameter("nome"));
        cliente.setEmail(request.getParameter("email"));
        cliente.setTelefone(request.getParameter("telefone"));
        cliente.setRg(request.getParameter("rg"));
        cliente.setLogin(request.getParameter("login"));
        cliente.setSenha(request.getParameter("senha"));
        cliente.setCpf(request.getParameter("cpf"));
        endereco.setRua(request.getParameter("rua"));
        endereco.setNumero(request.getParameter("numero"));
        endereco.setBairro(request.getParameter("bairro"));
        endereco.setCidade(request.getParameter("cidade"));
        endereco.setEstado(request.getParameter("estado"));
        endereco.setPais(request.getParameter("pais"));
        perfil.setId(Integer.parseInt(request.getParameter("idPerfil")));
        cliente.setPerfil(perfil);
        cliente.setEndereco(endereco);
    }

    private void pesquisaPorNome() {
        clienteDAO = new ClienteDAOImp();
        try {
            String nome = request.getParameter("nome");
            List clientes = clienteDAO.pesquisaPorNome(nome);
            request.setAttribute("clientes", clientes);
            rd = request.getRequestDispatcher("/pesqCliente.jsp");
        } catch (Exception e) {
            System.out.println("Erro ao pesquisar cliente " + e.getMessage());
        }
    }

    private void carregaCombo() {
        perfilDAO = new PerfilDAOImp();
        try {
            List perfis = perfilDAO.listar();
            request.setAttribute("perfis", perfis);
            rd = request.getRequestDispatcher("cadCliente.jsp");
        } catch (Exception e) {
            System.out.println("Erro ao carregar combo " + e.getMessage());
        }
    }

    private void altera() {
        carregaCliente();
        clienteDAO = new ClienteDAOImp();
        try {
            clienteDAO.alterar(cliente);
            request.setAttribute("msg", "Cliente alterado com sucesso !");
            rd = request.getRequestDispatcher("/index.jsp");
        } catch (Exception ex) {
            Logger.getLogger(ClienteServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void pesquisaClientePorId() {
        clienteDAO = new ClienteDAOImp();
        int id = Integer.parseInt(request.getParameter("id"));
        try {
            cliente = (Cliente) clienteDAO.procurar(id);
            request.setAttribute("cliente", cliente);
            rd = request.getRequestDispatcher("altCliente.jsp");
        } catch (Exception ex) {
            Logger.getLogger(CategoriaServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.request = request;
        this.response = response;
        processRequest();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.request = request;
        this.response = response;
        processRequest();
    }
}